package com.adee.design.action.promise;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;

/**
 * 自定义任务类，可同步执行，也可异步执行
 * @param <T>
 * @param <R>
 */
public class MyTask<T, R> {
    private static AtomicInteger threadCounter = new AtomicInteger(1);
    private Function<T, R> func;
    public MyTask(Function<T, R> func) {
        this.func = func;
    }
    // 同步执行
    public R run(T t) {
        return func.apply(t);
    }
    // 异步执行，自己启动一个线程
    public IPromise<R> runAsync(T t) {
        MyPromise<R> promise = new MyPromise<>();
        Lock lock = promise.getLock();
        Condition done = promise.getCondition();
        Thread thread = new Thread(() -> {
            lock.lock();
            try {
                R data = func.apply(t);
                promise.setData(data);
                promise.getDone().set(true);
                done.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "Thread-MyTask-" + threadCounter.getAndIncrement());
        thread.start();
        return promise;
    }
}
